//
//  NetAction.swift
//  swifttest1
//
//  Created by kologe on 2024/9/16.
//



import Foundation
import Network

class NetMessage:ObservableObject{
    
    //单例模式
    private static var sharedInstance:NetMessage = NetMessage()

    static public func shared() -> NetMessage{
        return sharedInstance;
    }
    
    init() {
        self.hostName = getTempName()
        self.tcpPort = getTcpPort()
    }
    
    @Published var hostName:String = "nil"
    @Published var tcpPort:UInt16 = 13531
    
    
    func getIPAddress() -> String {
        var address: String = ""
        var ifaddr: UnsafeMutablePointer<ifaddrs>?
        
        if getifaddrs(&ifaddr) == 0 {
            var ptr = ifaddr
            while ptr != nil {
                defer { ptr = ptr?.pointee.ifa_next }
                
                guard let interface = ptr?.pointee else { continue }
                let addrFamily = interface.ifa_addr.pointee.sa_family
                
                // Check for IPv4 and IPv6
                if addrFamily == UInt8(AF_INET)  {
                    let name = String(cString: interface.ifa_name)
                    let flags = interface.ifa_flags
                    //非打开和非活动的都不采用
                    if flags & UInt32(IFF_UP) == 0 || flags & UInt32(IFF_RUNNING) == 0 {
                        continue
                    }
                    if name.hasPrefix("en") {
                        var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                        getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.pointee.sa_len), &hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST)
                        address = String(cString: hostname)
                    }
                    
                }
            }
            freeifaddrs(ifaddr)
        }
        
        return address
    }
    func getTempName()->String{
        do{
            if let filePath = Bundle.main.path(forResource: "English_Cn_Name_Corpus", ofType: "txt") {
                print("File path: \(filePath)")
                let fileContent = try String(contentsOfFile: filePath, encoding: .utf8)
                let names = fileContent.components(separatedBy: .newlines).filter{ !$0.isEmpty }
                let randomInt = Int.random(in: 0..<names.count-1)
                let res = names[randomInt]
                return res
            } else {
                print("File not found.")
            }
            
            return "fes"
        }catch{
            // 处理错误
            error_log("Error reading file: \(error)")
            return "ffff"
        }
    }
    
    
   
    
  
    
    
   
    
}
